import {
  onSwitch,getProjectList,verifyCodeFun,changePassword
  } from './userListServ'
  // import { parse } from 'qs'
  import { message } from 'antd'
  // import moment from 'moment'
  import {isEmpty, isArray, cloneDeep, merge} from 'lodash'
  import $ from 'jquery';
  import axios from 'axios'
  import config from 'config/config'
  
  const defultState = {
      biz:{
        queryForm: {}
      },
      submitLoading: false,
      submitFeikongLoading: false,
      backLoading: false,
      id:"",
      areaList: [],
      products: [],
      otherQuery:{
        areaId:"",
        projectId:""
      }
  }
  
  const tmpModule = {
    state: cloneDeep(defultState),
    subscriptions: {
      setup ({dispatch, history}) {
        history.listen(({ pathname, query }) => {
          if('' + tmpModule.pathname === '' + pathname){
            if(query.areaId){
              defultState.otherQuery.areaId = query.areaId;
              defultState.otherQuery.projectId = query.projectId;
            }
            dispatch({type: 'updateStore', payload: cloneDeep(defultState)})
            dispatch({type: 'getProjectList', payload: {}})
          }
        })
      },
    },
  
  
    effects: {
      *down({payload}, {put, call, select}) {
          let {biz} = yield select(state => state[tmpModule.namespace])
          if(!biz.queryForm.projectId || !biz.queryForm.regionId){
            message.warn('请先选择区域和项目')
            return
          }
          if(!biz.selectedRows.length){
            message.warn('请先选择数据')
            return
          }
          let arr = []
          let arr1 = []
          let templist = biz.selectedRows.filter(item => item.appRoleZituo != '4')
          for(var pt of templist){
            arr.push(pt.phone)
            arr1.push(pt.name)
          }
          let params = {
            projectId: biz.queryForm.projectId,
            phones: arr.join(','),
            name: arr1.join(',')
          }
          let url = config.baseUrl+`zituo-admin/a/platform/userManager/generateQrCode`
          axios({
              method: 'post',
              url: url,
              responseType: 'blob',
              headers: {},
              data: params,
          }).then(res => {
              const content = res.data
              console.log(res)
              const blob = new Blob([content])
              Date.prototype.Format = function (fmt) { // author: meizz
                  var o = {
                      "M+": this.getMonth() + 1, // 月份
                      "d+": this.getDate(), // 日
                      "h+": this.getHours(), // 小时
                      "m+": this.getMinutes(), // 分
                      "s+": this.getSeconds(), // 秒
                      "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
                      "S": this.getMilliseconds() // 毫秒
                  };
                  if (/(y+)/.test(fmt))
                      fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
                  for (var k in o)
                      if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                          return fmt;
              }
              let dateTime = new Date().Format("yyyy-MM-dd hh:mm:ss");
              let fileName = `行销名片码 ${dateTime}.zip`
              if ('download' in document.createElement('a')) { // 非IE下载
                const elink = document.createElement('a')
                elink.download = fileName
                elink.style.display = 'none'
                elink.href = URL.createObjectURL(blob)
                document.body.appendChild(elink)
                elink.click()
                URL.revokeObjectURL(elink.href) // 释放URL 对象
                document.body.removeChild(elink)
              } else { // IE10+下载
                navigator.msSaveBlob(blob, fileName)
              }
              message.success('导出成功')
          })
      },
      //获取区域项目
      *getProjectList({payload},{put,select,call}){
        let {areaList,areaId} = yield select(state => state[tmpModule.namespace])
        let params = {
            level : payload.areaCode?4:2,
            companyguid:payload.areaCode?payload.areaCode: ''
          }
          if(yield call(verifyCodeFun,{})){
            const { data } = yield call(getProjectList, {...params})
            let list = data
            if(!list.length){
              return
            }
            areaList =  list.map((item,index)=>{
              return {
                label: item.buname,
                value: item.buguid,
                children: item.childSysUninessunitList
              }
            })
            yield put({type: 'updateStore', payload: {areaList}})
            yield put({type: 'filterProjectList', payload: {}})
          }
          
      },
      *onSwitch({payload},{put,select,call}){
        let params = payload
        const { success, msg, data } = yield call(onSwitch, {...params})
        let defultState = yield select(state => state[tmpModule.namespace])
        
        if(success){
          message.success('切换成功')
          defultState.biz.refreshListDatas(true)
        }
      },
      *changePassword({payload},{put,select,call}){
        let params = payload
        const { success, msg, data } = yield call(changePassword, {...params})
        let defultState = yield select(state => state[tmpModule.namespace])
        
        if(success&&data.i){
          message.success('重置密码成功')
          defultState.biz.refreshListDatas(true)
        }
      },
      *filterProjectList({payload},{put,select,call}){    
        let {products,areaList,biz} = yield select(state => state[tmpModule.namespace])
        let list = []
        for(var item of areaList){
          if(biz.queryForm.regionId&&item.value == biz.queryForm.regionId){
            list = item.children
          }
        }
        if(list.length){
          products =  list.map((item,index)=>{
            return {
              label: item.buname,
              value: item.buguid,
            }
          })
        }
        yield put({type: 'updateStore', payload: {products}})
      },
    },
    // 存入状态机
    reducers: {
      updateStore(preState, action) {
        return Object.assign({}, preState, action.payload)
      },
    }
  }
  
  export default tmpModule
  